package com.magold.circuit.module;

import org.andengine.engine.handler.IUpdateHandler;
import org.andengine.entity.sprite.Sprite;
import org.andengine.opengl.texture.region.ITextureRegion;
import org.andengine.opengl.vbo.VertexBufferObjectManager;

import com.badlogic.gdx.math.Vector2;

/**
 * 
 * 
 * @author Eternity
 *
 */
public class Wire extends Sprite {
	private CircuitModule mFirstModule;
	private CircuitModule mNextModule;
	
	public Wire(CircuitModule pFirst, CircuitModule pNext, ITextureRegion pTextureRegion, VertexBufferObjectManager pVertexBufferObjectManager) {
		super(0, 0, pTextureRegion, pVertexBufferObjectManager);
		registerUpdateHandler(new WirePositionSetter());
		mFirstModule = pFirst;
		mNextModule = pNext;
		setRotationCenter(0, 0);
		setScaleCenter(0, 0);
	}
	
	
	
	@Override
	public boolean equals(Object o) {
		if (o instanceof Wire) {
			Wire w = (Wire) o;
			return mFirstModule==w.mFirstModule && mNextModule==w.mNextModule;
		}
		
		return false;
	}

	@Override
	public int hashCode() {
		return mFirstModule.hashCode() | mNextModule.hashCode();
	}



	private class WirePositionSetter implements IUpdateHandler {
		private Vector2 mDirection = new Vector2();
		
		@Override
		public void onUpdate(float pSecondsElapsed) {
			setVisible(false);
			float[] in = mNextModule.getWireOutPosition();
			if (in == null) return;
			mDirection.set(in[0], in[1]);	// mDirection buffer the value in.
			
			float[] out = mFirstModule.getWireInPosition();
			if (out == null) return;
			
			setVisible(true);
			
			setPosition(out[0], out[1]);
			
			mDirection.sub(out[0], out[1]);
			double angle = Math.atan2(mDirection.y, mDirection.x);
			setRotation((float) Math.toDegrees(angle));
			
			float scale = mDirection.len() / getWidth();
			setScale(scale, 1);
		}

		@Override
		public void reset() {
		}
		
	}

}
